const Chrome = require('./chrome');
const moment = require('moment');
const AnchorTask = require('./Task/anchor');
const fs = require('fs');
const os = require('os');
const Core = require('./Core');

let chromePath, userPath = process.env.UNIX_USER_DATA_DIR;
let system = os.platform().toLowerCase();
if (system === 'win32') { //Windows
    chromePath = 'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe';
    userPath = process.env.WIN_USER_DATA_DIR;
} else if (system === 'linux') { //Linux
    chromePath = '/usr/bin/google-chrome';
} else if (system === 'darwin') { //Mac
    chromePath = '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome';
}

if (!chromePath || !fs.existsSync(chromePath))
    throw new Error('找不到Chrome');

const core = new Core();
const chrome = new Chrome({
    userPath,
    launch: {
        headless: false,
        executablePath: chromePath,
        args: [
            '--no-sandbox',
            '--mute-audio',
            '--disable-gpu',
            '--disable-setuid-sandbox',
            '--ignore-certificate-errors',
            '--ignore-ssl-errors',
            '--ignore-certificate-errors-spki-list',
            '--hide-scrollbars',
            // '--ppapi-flash-version=28.0.0.161',
            // '--ppapi-flash-path=/root/.config/google-chrome/PepperFlash/28.0.0.161/libpepflashplayer.so',
            '--user-data-dir=' + userPath,
        ]
    }
});

(async () => {
    await core.init();
    core.on('ready', config => {
        if (chrome.isReady) {
            chrome.reset();
            return;
        }
        chrome.__options.parallel = config.parallel;
        chrome.__options.parallel = 1;//同时执行任务的数量
        chrome.launch();
    });
    core.on('screenshot_anchor', command => {
        if (!chrome.isReady)
            return;
        console.log('截图命令', moment().format('YYYY-MM-DD HH:mm:ss'), JSON.stringify(command));
        (async () => {
            const res = await chrome.addTask(new AnchorTask(command.url));
            if (res) {
                command.buffer = res.buffer;
                core.emit('file', command);
            }
        })();
    });

    //每5秒上报队列中在等待的任务数量
    setInterval(() => {
        core.emit('task_length', chrome.state);
    }, 5000);

    core.on('restart', () => {
        console.log('重启命令', moment().format('YYYY-MM-DD HH:mm:ss'));
        chrome.close().then(() => {
            process.exit(0);
        });
    });
})();
//